package com.ant.myagile

import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.security.authentication.ProviderManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.context.SecurityContextHolder

import com.ant.myagile.utils.CommonUtils;

class LoginService {
	
	static transactional = true
	def springSecurityService
	
	ProviderManager authenticationManager;
	
	void setAuthenticationManager(ProviderManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}
	
	def checkExistAccount(username){
		def flag
		def checkMember = Member.findByUsername(username)
		if(checkMember != null){
			if(springSecurityService.encodePassword("").equals(checkMember.password))
				flag = 0
			else
				flag = 1
		}
		else flag = 2
		
		return flag
	}
	
	def sendMail(username, yourname,ServletContext context){
		MailService mailService = new MailService()
		def checkMember = Member.findByUsername(username)
		if(checkMember == null){
		Member member = Member.findByUsername(username)?: new Member(username: username, enabled: true).save(failOnError: true)
		def guestRole = Role.findByAuthority("ROLE_GUEST") ?: new Role(authority: "ROLE_GUEST").save(failOnError: true)
		if(!member.authorities.contains(guestRole)){
			MemberRole.create(member,guestRole)
		}
		def path=new MailService().realPath(context)
		def token = CommonUtils.randomToken()
		member.token = token
		member.tokenDate = new Date()
		member.save(failOnError: true)
		StringBuffer strbuf = new StringBuffer();
		strbuf.append("<h3>Welcome to My Agile!</h3>")
		strbuf.append("<p>Dear "+yourname+"</p>")
		strbuf.append("<p>Almost finished. We need to confirm your email address</p>")
		strbuf.append("<p><a href='"+path+"member/confirmUserEmail?tk="+token+"'>Please click here to confirm your email.</a></p>")
		mailService.sendMail("Welcome to My Agile! Please confirm your email",strbuf.toString(), username)
		}	
		
	}
	
	def sendMailForgetPassword(username, ServletContext context){
		MailService mailService = new MailService()
		def checkMember = Member.findByUsername(username)
		if(checkMember != null){
			def path = new MailService().realPath(context)
			StringBuffer strbuf = new StringBuffer();
			strbuf.append("<h3>Email to reset your password</h3>")
			strbuf.append("<p>Dear "+checkMember.firstName+"</p>")
			strbuf.append("<p>There was a request to reset password at My Agile. If it was you, please continue to process!</p>")
			strbuf.append("<p><a href='"+path+"member/resetPass?tk="+checkMember.tokenPass+"'>Please click here to reset your password and login to My Agile application.</a></p>")
			mailService.sendMail("Reset your password",strbuf.toString(), username)
		}
		return checkMember? true:false
	}
	
	def findMemberByUserName(){
		Member memberLogin = springSecurityService.currentUser
		Member member = Member.findByUsername(memberLogin?.username);
		return member?member:'';
	}
	
	def autoLogin(username, password){
		try {
			UsernamePasswordAuthenticationToken usernameAndPassword = new UsernamePasswordAuthenticationToken(username, password)
			Authentication auth = authenticationManager.doAuthentication(usernameAndPassword);
			SecurityContextHolder.getContext().setAuthentication(auth);
		}
		catch(AuthenticationException e){
				SecurityContextHolder.getContext().setAuthentication(null);
				log.error("Login failed after registration. This should never happen: ", e);
			}
	}
}
